//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package issue_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type SpritStateDbItem struct {
	SpritId        string `bson:"_id"`
	TaskCount      uint32 `bson:"taskCount"`
	TaskCountDirty bool   `bson:"taskCountDirty"`
	BugCount       uint32 `bson:"bugCount"`
	BugCountDirty  bool   `bson:"bugCountDirty"`
}

type _SpritStateDao struct {
	mc *mongo.Collection
}

func newSpritStateDao(db *mongo.Database) (*_SpritStateDao, error) {
	mc := db.Collection(db_ns.DB_NS_ISSUE + "sprit_state")
	return &_SpritStateDao{mc: mc}, nil
}

func (db *_SpritStateDao) Insert(ctx context.Context, dbItem *SpritStateDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_SpritStateDao) ListById(ctx context.Context, spritIdList []string) ([]*SpritStateDbItem, error) {
	if len(spritIdList) == 0 {
		return []*SpritStateDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": spritIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*SpritStateDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_SpritStateDao) Remove(ctx context.Context, spritId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": spritId})
	return err
}

func (db *_SpritStateDao) SetBugCount(ctx context.Context, spritId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": spritId}, bson.M{"$set": bson.M{"bugCount": count, "bugCountDirty": false}})
	return err
}

func (db *_SpritStateDao) SetTaskCount(ctx context.Context, spritId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": spritId}, bson.M{"$set": bson.M{"taskCount": count, "taskCountDirty": false}})
	return err
}

func (db *_SpritStateDao) MarkBugCountDirty(ctx context.Context, spritId string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": spritId}, bson.M{"$set": bson.M{"bugCountDirty": true}})
	return err
}

func (db *_SpritStateDao) MarkTaskCountDirty(ctx context.Context, spritId string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": spritId}, bson.M{"$set": bson.M{"taskCountDirty": true}})
	return err
}
